<?php

namespace app\service\admin\system;

use app\model\Common;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class RoleService
{

    /**
     * 列表
     * @param array $request
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getList(array $request): array
    {
        $page = $request['page'] ?? 1;
        $size = $request['size'] ?? 10;
        $res = Common::getList(RoleTable, [], ['id', 'name', 'menu_list', 'description', 'create_time'], $page, $size);
        if ($res['count'] > 0) {
            foreach ($res['data'] as &$v) {
                $v['menu_list'] = jsonToArray($v['menu_list']);
            }
        }
        return $res;
    }

    /**
     * 添加
     * @param array $request
     * @return int|string
     */
    public static function add(array $request)
    {
        $data = self::getRoleData($request);
        return Common::addData(RoleTable, $data);
    }

    /**
     * 修改
     * @param array $request
     * @return int
     * @throws DbException
     */
    public static function update(array $request): int
    {
        $data = self::getRoleData($request);
        return Common::updateData(RoleTable, ['id' => $request['id']], $data);
    }

    /**
     * 删除
     * @param array $request
     * @return false|int|string
     * @throws DbException
     */
    public static function delete(array $request)
    {
        if (!isset($request['data']) || !$request['data']) {
            return false;
        }
        $ids = [];
        foreach ($request['data'] as $v) {
            $ids[] = $v['id'];
        }
        return Common::deleteData(RoleTable, ['id' => $ids], true);
    }

    /**
     * 角色信息处理
     * @param array $request
     * @return array
     */
    private static function getRoleData(array $request): array
    {
        $menuIds = isset($request['menu_list']) ? self::getMenuIds($request['menu_list']) : [];
        return [
            'name' => $request['name'],
            'description' => $request['description'],
            'menu_list' => arrayToJson($menuIds),
        ];
    }

    /**
     * 获取选中菜单id
     * @param array $menuList
     * @param array $ids
     * @return array
     */
    private static function getMenuIds(array $menuList = [], array $ids = []): array
    {
        if (count($menuList) > 0) {
            foreach ($menuList as $v) {
                $ids[] = $v['id'];
                if (isset($v['children'])) {
                    $ids = self::getMenuIds($v['children'], $ids);
                }
            }
        }
        return $ids;
    }
}
